# coding:utf-8

import sys

sys.path.append('/mywork/gitcode-repository/hades/dev-project/adam/src/main/python')

from src.manager.log_manager import LogManager
from src.manager.oracle_manager import OracleManager
from src.manager.html_manager import HtmlManager
from src.config.oracle_config import OracleConfig
from src.model.stock_top_ranking import StockTopRanking
import time
import re

Logger = LogManager.get_logger(__name__)


class StockTopRankingHandler:
    """
    股票流行排名处理器
    """

    def __init__(self):
        """
        构造函数，初始化oracle_manager和cursor对象
        """
        self.oracle_manager = OracleManager(OracleConfig.Username, OracleConfig.Password, OracleConfig.Url)
        self.oracle_manager.connect()
        self.cursor = self.oracle_manager.get_cursor()

    def get_stock_info_list(self):
        """
        获取所有股票信息
        :return:
        """
        Logger.info('获取所有股票信息')

        self.cursor.execute('select * from stock_info')
        stock_info_list = self.cursor.fetchall()
        return stock_info_list

    def get_stock_search_result_number_by_stock_name(self, stock_name):
        """
        通过股票名称，获取股票搜索结果数量
        :param stock_name:
        :return:
        """
        Logger.info('通过股票名称【' + stock_name + '】，获取股票搜索结果数量')

        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
            "Accept-Encoding": "gzip, deflate",
            "Cache-Control": "max-age=0",
            "Connection": "keep-alive",
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
            "Host": "www.baidu.com",
            "Upgrade-Insecure-Requests": "1",
            "Cookie": "H_BDCLCKID_SF_BFESS=tRk8_ItMfCvDqTrP-trf5DCShUFsbU5lB2Q-XPoO3K8WDhTvbJJq5nFJjpjvWhcK3NTkBfbgylRM8P3y0bb2DUA1y4vpWfo3BmTxoUJ2-Mc0Ml_xqtnWWRkebPRiJPr9QgbqslQ7tt5W8ncFbT7l5hKpbt-q0x-jLTnhVn0MBCK0HPonHjuWDjOP; PSTM=" + str(int(time.time())) + "; shifen[7130721_91638]=" + str(int(time.time())) + "; BDSVRTM=359; BDSFRCVID_BFESS=pFFOJexroG38lIoewewyh7vXOYaDUYjTDYLtOwXPsp3LGJLVNAhMEG0PtsZz6B0-oxZxogKK0mOTHv-F_2uxOjjg8UtVJeC6EG0Ptf8g0M5; BA_HECTOR=ala004ag0k0l8haglk1g9q85g0r; H_PS_645EC=de18s9Y8OA1WMKBS1Slel3AqF%2FyQ1uCQy2qKmUDCE8D6WIUc9wRgbIMCuNw; BD_HOME=1; BAIDUID_BFESS=1C941E72A19E81B2C152056B3737832B:FG=1; H_BDCLCKID_SF=tRk8_ItMfCvDqTrP-trf5DCShUFsbU5lB2Q-XPoO3K8WDhTvbJJq5nFJjpjvWhcK3NTkBfbgylRM8P3y0bb2DUA1y4vpWfo3BmTxoUJ2-Mc0Ml_xqtnWWRkebPRiJPr9QgbqslQ7tt5W8ncFbT7l5hKpbt-q0x-jLTnhVn0MBCK0HPonHjuWDjOP; ab_sr=1.0.0_ZjQ3ZjYyZjE5NGJjMTBmOTVmNjcyMzM4YWM0ODU3NzNiZmE3ODczNWE4MjYyNWU3ODA3YjQ5NzdhYjUzMTI4MjcyNzVmYjdmNDkzYzhmNDhhNjQ1NGM2YWRmMDYyMDhl; PSINO=1; BIDUPSID=464AA52BCC756F77E2EA98AAAA4CA4DE; BAIDUID=464AA52BCC756F77E912329F2DFB4A55:FG=1; BD_CK_SAM=1; BCLID_BFESS=10105372249875337075; H_PS_PSSID=33839_33848_33855_33607_26350_33892; BDSFRCVID=pFFOJexroG38lIoewewyh7vXOYaDUYjTDYLtOwXPsp3LGJLVNAhMEG0PtsZz6B0-oxZxogKK0mOTHv-F_2uxOjjg8UtVJeC6EG0Ptf8g0M5; BCLID=10105372249875337075; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; delPer=0; __yjs_duid=1_a3491911dba11491b11a24f54a7de8821620909760641; BD_UPN=12314753"
        }
        url = 'http://www.baidu.com/s?wd=' + str(
            stock_name.encode()) + '&usm=3&rsv_idx=2&rsv_page=1'
        try:
            page_content = HtmlManager.get(url, headers)
            match = re.search('百度为您找到相关结果约(.*)个', page_content, flags=0)
            if match != None:
                search_result_number = int(match.group(1).replace(',', ''))
                Logger.info('股票【' + stock_name + '】的搜索结果数量为：' + str(search_result_number))
                return search_result_number
            else:
                Logger.warn('没有找到股票【' + stock_name + '】的搜索结果数量')
                return None
        except Exception as e:
            print(e)

    def get_stock_top_ranking_list_order_by_desc(self):
        """
        获取股票流行度排名，按降序排列
        :return:
        """
        Logger.info('获取股票流行度排名，按降序排列')

        # 获取所有股票信息
        stock_info_list = self.get_stock_info_list()

        # 查找所有股票的查询结果数量
        # 存储StockTopRanking对象列表
        stock_top_ranking_list = list()
        for stock_info in stock_info_list:
            # 获取每只股票的查询结果数量
            # time.sleep(random.randint(1, 60))
            search_result_number = self.get_stock_search_result_number_by_stock_name(stock_info[3])
            if search_result_number != None:
                stock_top_ranking = StockTopRanking(stock_info[2], stock_info[3], search_result_number)
                stock_top_ranking_list.append(stock_top_ranking)

        # 按照查询结果数量search_result_number，降序排列
        # return self.order_by_search_result_number_desc(stock_top_ranking_list)
        return stock_top_ranking_list

    def order_by_search_result_number_desc(self, stock_top_ranking_list):
        """
        按照查询结果数量search_result_number，降序排列
        :param stock_top_ranking_list:
        :return:
        """
        Logger.info('按照查询结果数量search_result_number，降序排列')

        for i in range(0, len(stock_top_ranking_list) - 1):
            for j in range(0, len(stock_top_ranking_list) - 1 - i):
                if stock_top_ranking_list[j].search_result_number < stock_top_ranking_list[j + 1].search_result_number:
                    temp = stock_top_ranking_list[j]
                    stock_top_ranking_list[j] = stock_top_ranking_list[j + 1]
                    stock_top_ranking_list[j + 1] = temp
        return stock_top_ranking_list

    def save_stock_top_ranking_list(self, stock_top_ranking_list):
        """
        保存StockTopRanking对象列表
        :return: 
        """
        Logger.info('保存StockTopRanking对象列表')

        for stock_top_ranking in stock_top_ranking_list:
            self.cursor.execute("select * from stock_top_ranking t where t.code_='" + stock_top_ranking.code + "'")
            result = self.cursor.fetchone()
            if result == None:
                param = [(stock_top_ranking.code, stock_top_ranking.name, stock_top_ranking.search_result_number)]
                self.oracle_manager.batch_insert("insert into stock_top_ranking(code_, name_, search_result_number) "
                                                 "values(:1, :2, :3)", param)
                Logger.info('股票【' + stock_top_ranking.to_str() + "】插入成功")
            else:
                Logger.info('股票【' + stock_top_ranking.to_str()+ "】已经存在")
